
import { 
  AmbientLight,
  ArrowHelper,
  BoxGeometry,
  Mesh,
  MeshBasicMaterial,
  MeshPhongMaterial,
  MeshNormalMaterial,
  PCFShadowMap,
  PerspectiveCamera,
  PlaneGeometry,
  Scene, 
  SphereGeometry, 
  SpotLight, 
  SpotLightHelper, 
  Vector3,
  WebGLRenderer
} from 'three'
import stats from '../utils/stats'
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'
import dat from 'dat.gui'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(-50, 75, 100)
camera.lookAt(new Vector3(10, 0, 0))

const renderer = new WebGLRenderer({ antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setClearColor(0x000000)
renderer.shadowMap.enabled = true
renderer.shadowMap.type = PCFShadowMap
document.body.appendChild(renderer.domElement)

const groundGeom = new PlaneGeometry(100, 100, 4, 4)
const groundMesh = new Mesh(groundGeom, new MeshPhongMaterial({
  color: 0x777777
}))
groundMesh.rotation.x = -Math.PI / 2
groundMesh.position.y = -20
groundMesh.receiveShadow = true
scene.add(groundMesh)

const group = new Mesh()
const mats = []

mats.push(new MeshBasicMaterial({
  color: 0x009e60
}))
mats.push(new MeshBasicMaterial({
  color: 0x0051ba
}))
mats.push(new MeshBasicMaterial({
  color: 0xffd500
}))
mats.push(new MeshBasicMaterial({
  color: 0xff5800
}))
mats.push(new MeshBasicMaterial({
  color: 0xc4e3a
}))
mats.push(new MeshBasicMaterial({
  color: 0xffffff
}))

for (let x = 0; x < 3; x++) {
  for (let y = 0; y < 3; y++) {
    for (let z = 0; z < 3; z++) {
      let cbueGeom = new BoxGeometry(2.9, 2.9, 2.9)
      let cube = new Mesh(cbueGeom, mats)
      cube.position.set(x * 3 -3, y* 3 -3, z*3 -3)
      cube.castShadow = true
      group.add(cube)
    }
  }
}

// x y z 放大2倍
group.scale.copy(new Vector3(2, 2, 2))
scene.add(group)

const spotLight = new SpotLight(0xffffff)
spotLight.position.set(-40, 60, -10)
spotLight.castShadow = true
spotLight.shadow.mapSize.set(1024, 1024)
spotLight.angle = 0.4
scene.add(spotLight)
scene.add(new SpotLightHelper(spotLight))

const controls = new function() {
  this.rotationSpeed = 0.02
  this.bouncingSpeed = 0.03
  this.selectedMesh = 'sphere'
}

const gui = new dat.GUI()
gui.add(controls, 'rotationSpeed', 0, 0.5)

const trackballControls = new TrackballControls(camera, renderer.domElement)

function render() {
  stats.update()
  trackballControls.update()

  group.rotation.y += controls.rotationSpeed
  group.rotation.x += controls.rotationSpeed
  group.rotation.z += controls.rotationSpeed

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}
render()